package com.ruicar.afs.cloud.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.admin.entity.SysParamInfo;
import com.ruicar.afs.cloud.admin.mapper.SysParamInfoMapper;
import com.ruicar.afs.cloud.admin.service.SysParamInfoService;
import com.ruicar.afs.cloud.common.datasync.componts.SyncHelper;
import com.ruicar.afs.cloud.components.datadicsync.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SysParamInfoServiceImpl extends ServiceImpl<SysParamInfoMapper, SysParamInfo> implements SysParamInfoService, ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void publishParamDataToSync() {
        new Thread(() -> {
            log.info("============参数同步========");
            try {
                Map<String, String> parmaMap = new HashMap<>();
                this.list().forEach(paramInfo -> {
                    parmaMap.put(paramInfo.getParamKey(),paramInfo.getParamValue());
                });
                JSONObject object = new JSONObject();
                object.put(Constants.PARAMS_KEYS.getKey(), parmaMap);
                SyncHelper.publishParams(Constants.PARAMS_KEYS, object);
            }catch (Exception e){
                log.error("参数同步失败",e);
            }
        }).start();
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.publishParamDataToSync();
    }
}
